/*
 * Copyright (c) 2025 李伟国
 * SQL-API is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.moyu.sql.business.controller;

import com.moyu.sql.business.entity.MoyuRouter;
import com.moyu.sql.business.entity.vo.MoyuRouterTree;
import com.moyu.sql.business.service.IMoyuRequestService;
import com.moyu.sql.business.service.IMoyuRouterService;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/moyu/router")
public class MoyuRouterController {

    @Resource
    private IMoyuRouterService moyuRouterService;

    @Resource
    private IMoyuRequestService moyuRequestService;

    /**
     * 获取所有路由的路由列表
     *
     * @return 路由列表
     */
    @GetMapping("list")
    public List<MoyuRouter> list() {
        return moyuRouterService.list();
    }

    /**
     * 获取路由树列表
     *
     * @return 路由树列表
     */
    @GetMapping("tree")
    public List<MoyuRouterTree> routerTree() {
        return moyuRouterService.getRouterTree();
    }

    /**
     * 获取路由详情
     *
     * @param id 路由 id
     * @return 路由详情
     */
    @GetMapping("/{id}")
    public MoyuRouter detail(@PathVariable String id) {
        return moyuRouterService.getById(id);
    }

    /**
     * 保存或更新路由
     *
     * @param moyuRouter 路由
     * @return 路由
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("")
    public MoyuRouter saveOrUpdate(@RequestBody MoyuRouter moyuRouter) {
        moyuRouterService.saveOrUpdate(moyuRouter);
        if(!ObjectUtils.isEmpty(moyuRouter.getIsRequest()) && moyuRouter.getIsRequest()){
            moyuRequestService.buildRequestRouterNode(moyuRouter);
        }
        return moyuRouter;
    }

    /**
     * 删除路由
     *
     * @param id 路由 id
     * @return 删除成功与否
     */
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable String id) {
        return moyuRouterService.removeById(id);
    }
}
